"""
通知管理路由
"""

from fastapi import APIRouter, HTTPException
from typing import Dict, Any, Optional

from ..models import BaseResponse, NotificationRequest
from ..services.notification_service import notification_service
from ..services.discovery_service import discovery_service
from ..logger import logger

router = APIRouter()


@router.post("/notifications/webhook", response_model=BaseResponse)
async def send_webhook_notification(notification: NotificationRequest):
    """发送Webhook通知"""
    try:
        # 构建通知载荷
        payload = {
            "event": notification.event_type,
            "model_id": notification.model_id,
            "model_name": notification.model_name,
            "server_id": notification.server_id,
            "timestamp": notification.timestamp,
            "data": notification.data
        }
        
        # 广播事件
        await notification_service.broadcast_event(payload)
        
        return BaseResponse(
            message=f"Webhook notification sent for event: {notification.event_type}"
        )
        
    except Exception as e:
        logger.error(f"Failed to send webhook notification: {e}")
        raise HTTPException(status_code=500, detail="Failed to send notification")


@router.post("/notifications/broadcast", response_model=BaseResponse)
async def broadcast_message(message: Dict[str, Any]):
    """广播消息到所有WebSocket连接"""
    try:
        await notification_service.send_websocket_message(message)
        
        return BaseResponse(
            message="Message broadcasted to all WebSocket connections"
        )
        
    except Exception as e:
        logger.error(f"Failed to broadcast message: {e}")
        raise HTTPException(status_code=500, detail="Failed to broadcast message")


@router.post("/notifications/client/{client_id}", response_model=BaseResponse)
async def send_client_message(client_id: str, message: Dict[str, Any]):
    """发送消息到特定客户端"""
    try:
        await notification_service.send_websocket_message(message, client_id)
        
        return BaseResponse(
            message=f"Message sent to client: {client_id}"
        )
        
    except Exception as e:
        logger.error(f"Failed to send message to client {client_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to send message")


@router.get("/notifications/stats", response_model=Dict[str, Any])
async def get_notification_stats():
    """获取通知统计信息"""
    try:
        stats = await notification_service.get_connection_stats()
        return {
            "success": True,
            "data": stats,
            "timestamp": __import__('time').time()
        }
        
    except Exception as e:
        logger.error(f"Failed to get notification stats: {e}")
        raise HTTPException(status_code=500, detail="Failed to get stats")


@router.post("/discovery/trigger", response_model=BaseResponse)
async def trigger_discovery():
    """手动触发模型发现"""
    try:
        await discovery_service.discover_all_servers()
        
        return BaseResponse(
            message="Model discovery triggered successfully"
        )
        
    except Exception as e:
        logger.error(f"Failed to trigger discovery: {e}")
        raise HTTPException(status_code=500, detail="Failed to trigger discovery")


@router.post("/discovery/server/{server_id}", response_model=Dict[str, Any])
async def discover_server_models(server_id: str):
    """发现指定服务器的模型"""
    try:
        result = await discovery_service.discover_server_now(server_id)
        
        return {
            "success": result["success"],
            "message": result["message"],
            "data": {
                "total_models": result.get("total_models", 0),
                "new_models": result.get("new_models", 0)
            },
            "timestamp": __import__('time').time()
        }
        
    except Exception as e:
        logger.error(f"Failed to discover server {server_id} models: {e}")
        raise HTTPException(status_code=500, detail="Failed to discover models")


@router.post("/events/model-update", response_model=BaseResponse)
async def trigger_model_update_event(
    model_id: str,
    model_name: str,
    server_id: str,
    data: Optional[Dict[str, Any]] = None
):
    """手动触发模型更新事件"""
    try:
        event_data = {
            "event_type": "model_update",
            "model_id": model_id,
            "model_name": model_name,
            "server_id": server_id,
            "timestamp": __import__('time').time(),
            "data": data or {}
        }
        
        await notification_service.broadcast_event(event_data)
        
        return BaseResponse(
            message=f"Model update event triggered for {model_name}"
        )
        
    except Exception as e:
        logger.error(f"Failed to trigger model update event: {e}")
        raise HTTPException(status_code=500, detail="Failed to trigger event")


@router.post("/events/model-discovered", response_model=BaseResponse)
async def trigger_model_discovered_event(
    model_id: str,
    model_name: str,
    server_id: str,
    data: Optional[Dict[str, Any]] = None
):
    """手动触发模型发现事件"""
    try:
        event_data = {
            "event_type": "model_discovered",
            "model_id": model_id,
            "model_name": model_name,
            "server_id": server_id,
            "timestamp": __import__('time').time(),
            "data": data or {}
        }
        
        await notification_service.broadcast_event(event_data)
        
        return BaseResponse(
            message=f"Model discovered event triggered for {model_name}"
        )
        
    except Exception as e:
        logger.error(f"Failed to trigger model discovered event: {e}")
        raise HTTPException(status_code=500, detail="Failed to trigger event")


@router.get("/events/test", response_model=BaseResponse)
async def test_event_system():
    """测试事件系统"""
    try:
        import time
        
        # 发送测试事件
        test_event = {
            "event_type": "system_test",
            "message": "This is a test event",
            "timestamp": time.time(),
            "data": {
                "test": True,
                "source": "api_test"
            }
        }
        
        await notification_service.broadcast_event(test_event)
        
        # 发送WebSocket测试消息
        test_message = {
            "type": "test",
            "message": "WebSocket test message",
            "timestamp": time.time()
        }
        
        await notification_service.send_websocket_message(test_message)
        
        return BaseResponse(
            message="Test events sent successfully"
        )
        
    except Exception as e:
        logger.error(f"Failed to send test events: {e}")
        raise HTTPException(status_code=500, detail="Failed to send test events")
